const app = getApp();
const qqmapsdk = app.globalData.qqmapsdk;
Page({
  data: {
    mapObj: {
      longitude: '113.12249',
      latitude: '23.00944',
      scale: 10,//缩放
      markers: [],
      polyline: [],
      enableTraffic: false,
    },
    mileage: '',//行驶里程
    EstimatedTime: '',// 预估时间
    quotation_Data: {
      zhongdianDatajw: [23.012491, 113.120541],
      qidianDatajw: [23.00944, 113.12249]
    },
    // 车辆选择
    carList: [],
    mainActiveIndex: 0,// 一级ID
    activeId: '',// 二级ID
    carListShow: false
  },
  onLoad (options) {
    let that = this;
    const eventChannel = this.getOpenerEventChannel();
    // eventChannel.on('quotation_Data', function (data) {
    //   that.setData({
    //     quotation_Data: data,
    //     ['mapObj.latitude']: data.qidianDatajw[0],
    //     ['mapObj.longitude']: data.qidianDatajw[1],
    //   }, () => {
    that.nearby_search()
    //   });
    // })
    that.getCarList()
  },

  getCarList () {
    let postData = { "oby": "e_chexingdengjibiao.row_id", "table_id": "e_chexingdengjibiao", "page": 1, "limit": 300, "SearchWhere": [] }
    wx.$post(3, 'DynamicQuery/query_dynamic_v1', postData).then(res => {
      if (res.response.errcode != 0 || res.errcode != 0) return wx.$toast(res.errmsg)
      if (res.data.row && res.data.row.length > 0) {
        let row = res.data.row, carList = [], carStateList = [];
        // 一级分类集合
        row.forEach(element => {
          carStateList.push(element.chexingdengjimingchen.substr(0, 2))
        })
        var carState = carStateList.filter((x, index, self) => self.indexOf(x) === index)
        // 一级分类push
        carState.forEach(element => {
          carList.push({
            text: element,
            // badge: 0,
            // dot: false,
            disabled: false,
            children: []
          })
        })
        // 二级分类push
        carList.forEach(element => {
          row.forEach(res => {
            if (element.text == res.chexingdengjimingchen.substr(0, 2)) {
              element.children.push({
                text: res.chexingdengjimingchen,
                id: res.chexingdengjibianhao,
                disabled: false
              })
            }
          })
        })
        this.setData({
          carList,
          activeId: carList[0].children[0].id,
          activeNames: carList[0].children[0].text
        })
      }
    })
  },
  // 事件触发，调用接口
  nearby_search: function () {
    var _this = this, tujingdian = [], { mapObj, quotation_Data } = _this.data, tujingdianString = ''
    if (quotation_Data.tujingdian && quotation_Data.tujingdian.length > 0) {
      quotation_Data.tujingdian.forEach(element => {
        tujingdian.push(`${element.tujingdianjw[0]},${element.tujingdianjw[1]}`)
      })
      if (tujingdian.length > 0) {
        tujingdianString = tujingdian.join(";")
      }
    }
    wx.showLoading()
    // 调用接口
    wx.$post(2, 'map/tencent/ws/direction/driving', {
      from: `${mapObj.latitude},${mapObj.longitude}`,
      waypoints: tujingdianString,
      to: `${quotation_Data.zhongdianDatajw[0]},${quotation_Data.zhongdianDatajw[1]}`
    }, false, true).then(res => {
      if (res.message != 'Success' && res.status != 0) return wx.$toast('路线规划失败')
      if (res.result.routes.length > 0) {
        var coors = res.result.routes[0].polyline, pl = [], data = res.result.routes[0];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        _this.setData({
          ['mapObj.polyline']: [{
            points: pl,
            color: '#58bc58',
            width: 8
          }],
          ['mapObj.markers']: [{
            id: 123,
            latitude: pl[0].latitude,
            longitude: pl[0].longitude,
            title: '起',
            iconPath: '/image/repairImg/qidian.png',
            width: 40,
            height: 40,
          },
          {
            id: 456,
            latitude: pl[pl.length - 1].latitude,
            longitude: pl[pl.length - 1].longitude,
            title: '终',
            iconPath: '/image/repairImg/zhongdian.png',
            width: 40,
            height: 40,
          },
          {
            id: 789,
            latitude: pl[0].latitude,
            longitude: pl[0].longitude,
            iconPath: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/car.png',
            width: 20,
            height: 20,
          },
          ],
          mileage: data.distance,//行驶里程
          EstimatedTime: _this.countDown(data.duration),// 预估时间
        })
        console.log(_this.countDown(data.duration), '查看分钟')
        wx.hideLoading()
      }
    })
  },
  countDown (minutes) {
    let hours = Math.floor(minutes / 60);
    let mins = minutes % 60;
    return `${hours}小时${mins}分钟`
  },

  onShow () {
  },
  onReady () {
    this.mapCtx = wx.createMapContext('quotation');
  },
  moveToLocation () {
    if (!this.data.mapObj.latitude || !this.data.mapObj.latitude) return wx.$toast("暂未获取到起点和终点")
    this.mapCtx.moveToLocation({
      latitude: this.data.mapObj.latitude,
      longitude: this.data.mapObj.longitude
    });
  },
  includePoints () {
    if (this.data.mapObj.polyline.length < 0 || this.data.mapObj.polyline[0].points.length < 0) return wx.$toast("路线规划出现错误")
    this.mapCtx.includePoints({
      points: this.data.mapObj.polyline[0].points,
      padding: [50, 50, 50, 50]
    });
  },
  isokEnableTraffic () {
    this.setData({
      ['mapObj.enableTraffic']: !this.data.mapObj.enableTraffic
    })
  },
  moveAlong () {
    if (this.data.mapObj.polyline.length < 0 || this.data.mapObj.polyline[0].points.length < 0) return wx.$toast("路线规划出现错误")
    this.mapCtx.moveAlong({
      markerId: 789,
      path: this.data.mapObj.polyline[0].points,
      duration: 12000
    });
  },
  onClickNav (e) {
    // 一级
    this.setData({ mainActiveIndex: e.detail.index })
  },
  onClickItem (e) {
    // 二级
    this.setData({ activeId: e.detail.id, activeNames: e.detail.text })
    this.setData({ carListShow: false })
  },
  carListShowClick () {
    this.setData({ carListShow: true })
  },
  onSubmit () {

  }
})